<template>
  <a-modal width="400px" v-model:visible="visible" :mask-closable="false" title="修改续租" @cancel="close" @close="close" unmount-on-close>
    <page-form :model="form" :rules="rules" ref="formRef" layout="vertical">
      <page-form-row :gutter="24">
        <page-form-item field="endTime" label="续租后还车时间" size="1">
          <template #label-extra>
            <div class="rent-days"> 续租时长：{{ form.rentDays || '- 天' }} </div>
          </template>
          <i-date-picker
            :disabledDate="disabledDate"
            class="w-full"
            :show-now-btn="false"
            v-model="form.endTime"
            value-format="YYYY-MM-DD"
            @change="changeTimeFn"
          />
        </page-form-item>
      </page-form-row>
      <page-form-row :gutter="24">
        <page-form-item label="续租备注" size="1">
          <i-textarea v-model="form.remark" />
        </page-form-item>
      </page-form-row>
    </page-form>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="ok" :loading="loading">确认</a-button>
    </template>
  </a-modal>
  <!-- 二次确认 -->
  <a-modal title="提示" v-model:visible="confirmVisible" :mask-closable="false" @cancel="onCancel" @close="onCancel" unmount-on-close>
    <div v-for="(it, i) in resultMsg" :key="i">{{ it }}</div>
    <div>请确认是否排车？</div>
    <template #footer>
      <a-button @click="onCancel">关闭</a-button>
      <a-button type="primary" @click="confirmSubmit">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import iTextarea from '@/views/order/short-order/components/i-textarea.vue'

  import { computed, ref, watch } from 'vue'
  import { computeRentDay, getLongOrderDetails, modifyReletCarTime } from '@/api/order/czsOrder'
  import dayjs from 'dayjs'
  import { platoonCarCheck } from '@/api/asset/carStock'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    details: {
      type: Object,
      default: () => ({}),
    },
    okLoading: {
      type: Boolean,
      default: false,
    },
  })

  const emits = defineEmits(['update:modelValue', 'update:okLoading', 'ok'])
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emits('update:modelValue', value),
  })
  const loading = computed({
    get: () => props.okLoading,
    set: (value) => emits('update:okLoading', value),
  })

  const orderInfo = ref<any>({})

  const formRef = ref()
  const form = ref<any>({})

  // 处理默认值
  // 租赁周期限制最小天数 1 天
  const timeRangeValidator = (value: string, callback: (param?: string) => void) => {
    if (value) {
      let start = props.details.startTime
      let end = value
      if (start && end) {
        let diff = dayjs(end).diff(dayjs(start))
        if (diff !== 0 && diff < 23 * 59 * 59 * 1000) {
          callback('续租时长最短为1天')
        }
      }
    }
    callback()
  }
  const rules = {
    endTime: [{ required: true, message: '请选择续租后还车时间' }, { validator: timeRangeValidator }],
  }

  const changeTimeFn = (value: string) => {
    if (value) {
      // 计算租期
      const param = {
        expectedUseCarTime: dayjs(props.details.startTime).format('YYYY-MM-DD 00:00:00'),
        expectedReturnCarTime: dayjs(value).format('YYYY-MM-DD 23:59:59'),
      }
      computeRentDay(param).then((res: any) => {
        let { dateStr, months } = res.result
        form.value.rentDays = dateStr
        form.value.rentMonths = months
      })
    } else {
      form.value.rentDays = undefined
    }
  }

  // disabled Date|Time
  const disabledDate = (dateVal: string) => {
    const prevDate = dayjs(props.details.startTime).format('YYYY-MM-DD 00:00:00')
    if (!dateVal || !prevDate) {
      return false
    }
    // 存在限制最大范围
    // 当前时间是 23:50
    if (dayjs(prevDate).hour() == 23 && dayjs(prevDate).minute() == 59) {
      return dayjs(prevDate).add(1, 'd').startOf('day').valueOf() > dayjs(dateVal).valueOf()
    } else {
      return dayjs(prevDate).startOf('day').valueOf() > dayjs(dateVal).valueOf()
    }
  }

  /** 获取续租信息 */
  const getReletInfo = (option: any) => {
    getLongOrderDetails({ id: option.orderId }).then((res: any) => {
      const result = res.result
      orderInfo.value = result.orderInfo

      // 初始化 endTime
      let endTime = props.details.endTime
      if (endTime) {
        form.value.endTime = dayjs(endTime).format('YYYY-MM-DD 23:59:59')
        changeTimeFn(form.value.endTime)
      }
      console.log('orderInfo', orderInfo.value, form.value)
    })
  }

  // 排车校验
  const resultMsg = ref([])
  const confirmVisible = ref(false)
  const platoonCarVerify = (callback: () => void) => {
    const params = {
      refId: orderInfo.value.id,
      startTime: dayjs(props.details.startTime).format('YYYY-MM-DD 00:00:00'),
      endTime: dayjs(form.value.endTime).format('YYYY-MM-DD 23:59:59'),
      useType: 3,
      carId: orderInfo.value.carId,
    }
    platoonCarCheck(params).then((res: any) => {
      let msgList = res.result.resultMsg || []
      if (msgList.length) {
        resultMsg.value = msgList
        confirmVisible.value = true
        return
      }
      callback && callback()
    })
  }

  // 续租
  const reletFn = () => {
    modifyReletCarTime({
      id: props.details.id,
      endTime: dayjs(form.value.endTime).format('YYYY-MM-DD 23:59:59'),
      remark: form.value.remark,
    })
      .then(() => {
        visible.value = false
        emits('ok')
      })
      .finally(() => {
        loading.value = false
      })
  }

  // 二次询问确认
  const confirmSubmit = () => {
    reletFn()
  }
  const onCancel = () => {
    confirmVisible.value = false
    loading.value = false
  }

  const ok = () => {
    formRef.value.validate((error: any) => {
      if (!error) {
        loading.value = true
        platoonCarVerify(() => {
          reletFn()
        })
      }
    })
  }

  const close = () => {
    visible.value = false
    loading.value = false
  }

  watch(
    () => props.details,
    (newVal) => {
      if (newVal) {
        form.value.remark = newVal.remark
        getReletInfo(newVal)
      }
    },
    { immediate: true, deep: true }
  )
</script>

<style lang="less" scoped>
  .rent-days {
    color: rgb(var(--primary-6));
  }
</style>
